package xyz.labmem.app.tray

import com.dustinredmond.fxtrayicon.FXTrayIcon
import javafx.application.Platform
import javafx.stage.Stage
import xyz.labmem.app.config.AppConfig
import xyz.labmem.common.property.ContextProperty.forwardNumProperty
import xyz.labmem.common.property.ContextProperty.reverseNumProperty
import xyz.labmem.common.property.ContextProperty.serverStatusProperty
import xyz.labmem.util.getResourceFile
import xyz.labmem.util.viewRun
import java.awt.Image
import java.awt.SystemTray
import java.awt.Toolkit
import java.awt.TrayIcon
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent


class AppTray(private val mainStage: Stage) {

    init {

        if (FXTrayIcon.isSupported()) {

            val trayMenuManager = TrayMenuManager()

            // 获取系统托盘实例
            val tray = SystemTray.getSystemTray()
            Platform.setImplicitExit(false)
            // 加载托盘图标
            val image: Image = Toolkit.getDefaultToolkit().createImage(getResourceFile(AppConfig.trayIcon).url)
            val trayIcon = TrayIcon(image, "我的应用")
            trayIcon.setImageAutoSize(true)
            // 鼠标监听器 - 右键显示自定义菜单
            trayIcon.addMouseListener(object : MouseAdapter() {
                override fun mouseClicked(e: MouseEvent) {
                    if (e.getButton() == MouseEvent.BUTTON3) { // 右键
                        viewRun {
                            // 获取鼠标位置并显示菜单
                            trayMenuManager.showMenu(e.xOnScreen.toDouble(), e.yOnScreen.toDouble())
                        }
                    }
                }
            })

            // 双击左键显示主窗口
            trayIcon.addActionListener { e ->
                viewRun {
                    try {
                        if (mainStage.isIconified) {
                            mainStage.setIconified(false);
                        }
                        if (!mainStage.isShowing) {
                            mainStage.show();
                        }
                        mainStage.toFront()
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
            }
            // 添加托盘图标
            tray.add(trayIcon)

            fun onChange() {
                trayIcon.toolTip =
                    """
                ${AppConfig.appName}
                服务状态：${if (serverStatusProperty.value()) "前进四" else "漫游中"}
                正向连接：${forwardNumProperty.value().toInt()}
                反向连接：${reverseNumProperty.value().toInt()}
            """.trimIndent()
            }
            onChange()
            serverStatusProperty.addListen { onChange() }
            forwardNumProperty.addListen { onChange() }
            reverseNumProperty.addListen { onChange() }

        }

    }

}